<template>
  <div class="container">
    <div class="app-container">
      <div class="role-class">
        <el-button type="primary" @click="dialogVisible = true">添加角色</el-button>
      </div>

      <el-table :data="roleList">
        <el-table-column prop="name" label="角色" width="200" align="center">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.rowData.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="启用" width="200" align="center">
          <template #default="{row}">
            <el-switch v-if="row.isEdit" v-model="row.rowData.state" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state === 1 ? '已启用' : (row.state === 0 ? '未启用':'无') }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" align="center">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model="row.rowData.description" size="mini" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{row}">

            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="btnEdit(row)">确认</el-button>
              <el-button size="mini" @click="row.isEdit = false">再想想</el-button>
            </template>

            <template v-else>
              <el-button size="mini" type="text" @click="assignPermissions(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="editRowData(row)">编辑</el-button>
              <!-- <el-button size="mini" type="text">删除</el-button> -->
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="再想想"
                icon="el-icon-info"
                icon-color="red"
                title="你确定要删除该角色吗？"
                @onConfirm="confirmOk(row.id)"
              >
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>

          </template>
        </el-table-column>
      </el-table>

      <el-row type="flex" justify="end" style="height: 60px;" align="middle">
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          layout="prev,pager,next"
          :total="pageParams.total"
          @current-change="pageChange"
        />
      </el-row>
    </div>

    <RoleDialog :dialog-visible.sync="dialogVisible" @updateRoleList="updateRoleList" />

    <el-dialog title="分配权限" :visible.sync="permissionDialog">
      <!-- 分配权限弹框 -->
      <!-- 树型组件 -->
      <el-tree
        ref="roleTreePerm"
        node-key="id"
        :data="permissionList"
        :props="{label:'name'}"
        show-checkbox
        default-expand-all
        check-on-click-node
        :default-checked-keys="permIds"
        check-strictly
        :expand-on-click-node="false"
      />

      <el-row type="flex" justify="center" align="middle">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="submitRolePerm">确认</el-button>
          <el-button size="mini" @click="permissionDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList, updateRole, delRole, roleDetail, assignPerm } from '@/api/role'
import RoleDialog from '@/views/role/components/Role-Dialog.vue'
import { getPermissionList } from '@/api/permission'
import { queryListBytree } from '@/utils'
export default {
  name: 'Role',
  components: {
    RoleDialog
  },
  data() {
    return {
      roleList: [],
      pageParams: {
        page: 1,
        pagesize: 5,
        total: null
      },
      dialogVisible: false,
      permissionDialog: false,
      permissionList: [],
      roleId: null,
      permIds: []
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    // 点击编辑行
    editRowData(row) {
      row.isEdit = true
      row.rowData.name = row.name
      row.rowData.state = row.state
      row.rowData.description = row.description
    },

    async confirmOk(id) {
      // 调用删除接口
      await delRole(id)
      this.$message.success('删除成功')
      if (this.roleList.length === 1) {
        this.pageParams.page--
      }
      this.getRoleList()
    },

    updateRoleList() {
      this.getRoleList()
    },
    async getRoleList() {
      try {
        const { rows, total } = await getRoleList(this.pageParams)
        this.roleList = rows
        this.roleList.forEach(item => {
          // 将数据变为响应式
          this.$set(item, 'isEdit', false)
          this.$set(item, 'rowData', {
            name: item.name,
            state: item.state,
            description: item.description
          })
        })
        this.pageParams.total = total
      } catch (error) {
        this.$message.error('获取角色数据失败')
      }
    },
    pageChange(value) {
      this.pageParams.page = value
      this.getRoleList()
    },
    async btnEdit(row) {
      // 先手动校验rowData的数据是否符合规范
      if (row.rowData.name && row.rowData.description) {
      // do something
      // 将数据发送到后台进行修改
        await updateRole({ ...row.rowData, id: row.id })
        this.$message.success('修改角色成功')
        // 将row.rowdata赋值给row
        Object.assign(row, {
          ...row.rowData,
          isEdit: false
        })
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async assignPermissions(id) {
      this.roleId = id
      const { permIds } = await roleDetail(id)

      this.permIds = permIds
      this.permissionList = queryListBytree(await getPermissionList(), 0)
      this.permissionDialog = true
    },
    async  submitRolePerm() {
      await assignPerm({
        id: this.roleId,
        permIds: this.$refs.roleTreePerm.getCheckedKeys()
      })
      this.$message.success('修改角色权限成功')
      this.permissionDialog = false
    }
  }
}
</script>

<style scoped>
.role-class{
  padding: 10px;
}
</style>
